<template>
	<view id="box">
		<!-- 自定义的顶部导航栏 -->
		<view class="top-view">
			<!-- 标题部分 -->
			<view :style=" 'height:' + total_height + 'px' ">
				<!-- 胶囊距离顶部的位置，要撑开 -->
				<view :style=" 'height:' + b_top + 'px'"></view>
				<!-- 和胶囊对齐的文字 -->
				<view :style=" ['height:' + b_height + 'px','line-height:' + b_height + 'px','padding-left:10px'] ">
					内江师范零食小店
				</view>
			</view>
		</view>

		<!-- 累计收益模块 -->
		<view class="profit-view" :style=" 'top:' + profit_top + 'px' ">
			<!-- 收益总额 -->
			<view class="profit-num">
				<text>累计收益(元)</text>
				<text>{{income}}</text>
			</view>

			<!-- 订单数量、销售额等 -->
			<view class="profit-sale">
				<view>
					<text>今日销售额</text>
					<text>{{sales}}</text>
				</view>
				<view>
					<text>今日订单数</text>
					<text>{{order_today}}</text>
				</view>
				<view>
					<text>累计订单数</text>
					<text>{{order_total}}</text>
				</view>
			</view>
		</view>

		<!-- 功能模块 -->
		<view class="function-options" :style=" 'top:' + options_top + 'px' ">
			<view v-for="(item,index) in options_list" :key="item.id" @click="goPage(index)">
				<image :src="item.image" mode="aspectFit"></image>
				<text>{{item.name}}</text>
			</view>
		</view>

	</view>



</template>

<script setup>
	import { onMounted, reactive, toRefs } from "vue"
	import { onPullDownRefresh } from '@dcloudio/uni-app'

	//存储要使用胶囊按钮的位置数据
	const data = reactive({
		b_height: 0, //胶囊的高度
		b_top: 0, //按钮距离顶部的高度
		total_height: 0, //自定义导航栏的总高度
		profit_top: 0, //订单收益距离顶部距离
		options_top: 0, //功能模块距离手机顶部的距离

		income: '0.00', // 收益
		sales: '0.00', // 今日销售额
		order_today: 0, // 今日订单数
		order_total: 0, // 累计订单数

		options_list: [ //功能列表
			{
				id: 1,
				image: '/static/images/banner.svg',
				name: '横幅管理'
			},
			{
				id: 2,
				image: '/static/images/seckill.svg',
				name: '秒杀管理'
			},
			{
				id: 3,
				image: '/static/images/commodity.svg',
				name: '商品管理'
			},
			{
				id: 4,
				image: '/static/images/order.svg',
				name: '订单管理'
			},
			{
				id: 5,
				image: '/static/images/classification.svg',
				name: '分类管理'
			}
		],


	})
	// toRefs 解构一下
	const { b_height, b_top, total_height, profit_top, options_top, options_list, income, sales, order_today, order_total } = toRefs(data)


	onMounted(() => {
		capsule()
		profitHeight()
		calculate()
	})
	// 下拉刷新
	onPullDownRefresh(()=>{
		console.log("下拉了");
		calculate()
	})

	// 1、获取胶囊按钮的位置信息
	function capsule() {
		// #ifndef APP-PLUS || H5 || MP-ALIPAY
		// 获取胶囊位置,API getMenuButtonBoundingClientRect 只有在微信小程序运行的时候才会生效，H5端查看会报错
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		// console.log("menuButtonInfo", menuButtonInfo);
		data.b_top = menuButtonInfo.top
		data.b_height = menuButtonInfo.height
		data.total_height = data.b_top + data.b_height
		data.profit_top = data.b_top + data.b_height + 20
		// #endif
	}

	// 2、计算累计收益板块的高度
	function profitHeight() {
		//uniapp中没有window对象和dom元素,所以使用 api 获取节点的一些几何信息
		const query = uni.createSelectorQuery()
		query.select(".profit-view").boundingClientRect((res) => {
			// console.log("res", res);
			data.options_top = res.height + data.profit_top + 10
		}).exec()
	}

	// 3、跳转界面
	function goPage(index) {
		switch (index) {
			case 0:
				uni.navigateTo({
					url: "/pages/banner/banner"
				})
				break;
			case 1:
				uni.navigateTo({
					url: "/pages/seckill/seckill"
				})
				break;
			case 2:
				uni.switchTab({
					url: "/pages/commodity/commodity"
				})
				break;
			case 3:
				uni.switchTab({
					url: "/pages/order/order"
				})
				break;
			case 4:
				uni.navigateTo({
					url: "/pages/classification_management/classification_management"
				})
				break;
			default:
				break;
		}
	}

	// 4、计算累计收益，今日销售额，今日订单数，累计订单数
	// 引入云函数初始化,用于操作数据库
	import { init } from "../../public/package-js/init.js"
	import moment from 'moment'
	moment.locale('zh-cn');

	async function calculate() {
		let db = await init()
		// 使用累计操作符 sum
		const $ = db.database().command.aggregate

		/* （1）计算累计收益 */
		const _ = db.database().command;
		const income = await db.database().collection('order_data').aggregate()  // 聚合操作
			.match({ // 匹配支付成功且没有退款的订单
				pay_status: 1,
				deliver_status: _.neq(3).and(_.neq(4))
			})
			.group({
				_id: null,
				totalPrice:$.sum('$subtotal')
			})
			.end()
			
		data.income = income.list.length === 0 ? '0.00' : parseFloat((income.list[0].totalPrice).toFixed(10))

		/* （2）今日销售额 */
		let query_time = moment().utcOffset(8).format('YYYY-MM-DD')
		const sales = await db.database().collection('order_data').aggregate()  
			.match({
				query_time,
				pay_status: 1,
				deliver_status: _.neq(3).and(_.neq(4))
			})
			.group({
				_id: null,
				totalPrice: $.sum('$subtotal')
			}).end()
		// console.log("sales",sales);
		data.sales = sales.list.length === 0 ? '0.00' : parseFloat((sales.list[0].totalPrice).toFixed(10))

		/* （3）今日订单数 */
		const orders = await db.database().collection('order_data').where({ query_time }).count()
		// console.log("order",orders);
		data.order_today = orders.total

		/* （4） 累计订单数 */
		const order_num = await db.database().collection('order_data').count()
		// console.log("order_num",order_num);
		data.order_total = order_num.total
		
		uni.stopPullDownRefresh()
	}
	

</script>

<style>
	page {
		background-color: #f4f4f4;
	}

	#box {
		position: relative;
	}

	/* 顶部渐变背景部分 */
	.top-view {
		height: 330rpx;
		background-image: linear-gradient(to top, #9be15d 0%, #00e3ae 100%);
	}

	/* 订单收益板块 */
	.profit-view {
		background-color: #FFFFFF;
		position: absolute;
		left: 20rpx;
		right: 20rpx;
		border-radius: 10rpx;
		padding: 20rpx;
	}

	.profit-num {
		display: flex;
		flex-direction: column;
		padding-bottom: 10rpx;
	}

	.profit-num text:nth-child(1) {
		font-size: 38rpx;
	}

	.profit-num text:nth-child(2) {
		font-size: 38rpx;
		padding-top: 18rpx;
	}

	.profit-sale {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.profit-sale view {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 10rpx;
		font-size: 34rpx;
	}

	.profit-sale view text:nth-child(1) {
		color: #a7a7a7;
		padding-bottom: 10rpx;
	}

	.profit-sale view text:nth-child(2) {
		font-weight: bold;
	}

	/* 功能部分 */
	.function-options {
		background-color: #FFFFFF;
		margin: 0 20rpx 20rpx 20rpx;
		border-radius: 10rpx;
		display: flex;
		flex-wrap: wrap;
		position: absolute;
		left: 0;
		right: 0;
		color: #555555;
	}

	.function-options image {
		width: 55rpx;
		height: 55rpx;
		display: block;
		margin-bottom: 20rpx;
	}

	.function-options view {
		width: calc(25% - 10rpx*2);
		margin: 20rpx 10rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
</style>
